import React, { useState, useEffect } from 'react';
import { Card, Image, Typography, Spin, message, Button } from 'antd';
import { CalendarOutlined, ShareAltOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { useParams, history } from '@umijs/max';
import { getDynamicDetail, DynamicInfo } from '@/services/DynamicService';
import { FileDetail } from '@/services/index';
import styles from './detail.less';
import dayjs from 'dayjs';
import { isMobile } from '@/utils';
import ReactPlayer from 'react-player';

const { Title, Paragraph } = Typography;

const DynamicDetail: React.FC = () => {
    const { idBase64 } = useParams<{ idBase64: string }>();
    const [loading, setLoading] = useState(false);
    const [detail, setDetail] = useState<DynamicInfo>();

    useEffect(() => {
        const fetchDetail = async () => {
            if (!idBase64) return;
            try {
                setLoading(true);
                const data = await getDynamicDetail(parseInt(atob(idBase64)));
                setDetail(data);
            } catch (error) {
                console.error('获取动态详情失败：', error);
            } finally {
                setLoading(false);
            }
        };

        fetchDetail();
    }, [idBase64]);

    const formatDate = (timestamp: string) => {
        return dayjs(parseInt(timestamp)).format('YYYY-MM-DD HH:mm');
    };

    // 兼容性处理：使用传统方式复制
    const fallbackCopyToClipboard = (text: string) => {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        try {
            document.execCommand('copy');
            message.success('链接已复制到剪贴板');
        } catch (err) {
            message.error('复制失败，请手动复制');
        }
        document.body.removeChild(textArea);
    };

    // 复制到剪贴板
    const copyToClipboard = (text: string) => {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text)
                .then(() => {
                    message.success('链接已复制到剪贴板');
                })
                .catch(() => {
                    fallbackCopyToClipboard(text);
                });
        } else {
            fallbackCopyToClipboard(text);
        }
    };

    const renderMediaGrid = (imageList: FileDetail[] = [], videoList: FileDetail[] = []) => {
        if (imageList?.length === 0 && videoList?.length === 0) return null;

        return (
            <div className={styles.mediaContent}>
                {/* 图片预览组 */}
                {imageList?.length > 0 && (
                    <div className={styles.mediaGrid}>
                        <Image.PreviewGroup>
                            {imageList.map((image) => (
                                <div key={image.id} className={styles.mediaWrapper}>
                                    <div className={styles.imageItem}>
                                        <Image
                                            src={`/api/file/play/${image.id}`}
                                            alt=""
                                        />
                                    </div>
                                </div>
                            ))}
                        </Image.PreviewGroup>
                    </div>
                )}

                {/* 视频列表 */}
                {videoList?.length > 0 && (
                    <div className={styles.videoList}>
                        {videoList.map((video) => (
                            <div key={video.id} className={styles.videoWrapper}>
                                <ReactPlayer
                                    url={`/api/file/play/${video.id}`}
                                    controls
                                    width="100%"
                                    height="100%"
                                    config={{
                                        file: {
                                            attributes: {
                                                controlsList: 'nodownload',
                                                disablePictureInPicture: true,
                                            },
                                        },
                                    }}
                                />
                            </div>
                        ))}
                    </div>
                )}
            </div>
        );
    };

    // 处理分享功能
    const handleShare = () => {
        const currentUrl = window.location.href;

        if (isMobile()) {
            // 移动端：使用原生分享API或复制到剪贴板
            if (navigator.share) {
                navigator.share({
                    title: detail?.title || '动态分享',
                    text: detail?.content || '',
                    url: currentUrl,
                }).catch(() => {
                    copyToClipboard(currentUrl);
                });
            } else {
                copyToClipboard(currentUrl);
            }
        } else {
            // PC端：直接复制链接
            copyToClipboard(currentUrl);
        }
    };


    return (
        <div className={styles.container}>
            <div className={styles.content}>
                <Button
                    type="link"
                    icon={<ArrowLeftOutlined />}
                    onClick={() => history.back()}
                    style={{marginTop: '15px' }}
                >
                    返回
                </Button>
                <Spin spinning={loading}>
                    {detail && (
                        <Card bordered={false} className={styles.detailCard}>
                            <div className={styles.header}>
                                <div className={styles.authorInfo}>
                                    {/* <div className={styles.authorName}>鞠婧祎</div> */}
                                    {detail.title && (
                                        <Title level={3} className={styles.title}>
                                            {detail.title}
                                        </Title>
                                    )}
                                    <div className={styles.postTime}>
                                        <CalendarOutlined /> {formatDate(detail.date)}
                                    </div>
                                </div>
                            </div>

                            <div className={styles.body}>
                                <Paragraph className={styles.text}>
                                    {detail.content}
                                </Paragraph>
                                {renderMediaGrid(detail.imageList, detail.videoList)}
                            </div>

                            <div className={styles.footer}>
                                <div className={styles.shareAction} onClick={handleShare}>
                                    <ShareAltOutlined /> 分享
                                </div>
                            </div>
                        </Card>
                    )}
                </Spin>
            </div>
        </div>
    );
};

export default DynamicDetail; 